package edu.zhuoxun.blogserver.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.zhuoxun.blogserver.entity.Result;
import edu.zhuoxun.blogserver.entity.Role;
import edu.zhuoxun.blogserver.entity.RolePermissions;
import edu.zhuoxun.blogserver.entity.User;
import edu.zhuoxun.blogserver.map.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class RoleController {
    @Resource
    public RoleMapper roleMapper;

    @GetMapping("/api/role/list")
    @ResponseBody
    public Result<List<Role>> getAllRoles(){
        Result<List<Role>> result = new Result<>();
        result.setCode(200);
        result.setMessage("OK");
        result.setData(roleMapper.selectList(new QueryWrapper<>()));
        return result;
    }

    @PostMapping("/api/role/has")
    @ResponseBody
    public Result<List<Role>> getHasRoles(@RequestBody User user) {
        Result<List<Role>> result = new Result<>();
        result.setCode(200);
        result.setMessage("OK");
        result.setData(roleMapper.getUserRole(user));
        return result;
    }

    @PostMapping("/api/role/save")
    @ResponseBody
    public Result<Void> saveRole(@RequestBody RolePermissions rolePermissions) {
        Result<Void> result = new Result<>();
        Role role = rolePermissions.getRole();
        if (role.getId() == null) {
            roleMapper.insert(role);
        } else {
            roleMapper.updateById(role);
        }
        roleMapper.deleteHasPermissions(role);
        roleMapper.insertHasPermissions(rolePermissions);
        result.setCode(200);
        result.setMessage("OK");
        return result;
    }
    @PostMapping("api/role/delete")
    @ResponseBody
    public Result<Void> deleteRoles(@RequestBody List<Role> roles) {
        Result<Void> result = new Result<>();
        boolean hasSuper = roles.stream().anyMatch(role -> role.getId() == 1);
        if (hasSuper) {
            result.setCode(500);
            result.setMessage("超级管理员无法删除");
        } else {
            roleMapper.deleteBatchIds(roles.stream().map(Role::getId).collect(Collectors.toList()));
            result.setCode(200);
            result.setMessage("OK");
        }
        return result;
    }
}
